/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utilities;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HtmlTable
{
    /*
     * This method formats a result set table into an html table format.
     * It assumes the table includes in column 1 an Id column, and omits that columns
     * from the output.
     */
    public static String FromResultSet(ResultSet resultSet)
    {
        try 
        {
            StringBuilder htmlRows = new StringBuilder();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            htmlRows.append("<table cellpadding='5' border='1' align='center'>");

            htmlRows.append("<tr align=\"center\">");
            for (int i = 2; i <= columnCount ; i++)
            {
                String columnName = metaData.getColumnName(i);
                columnName = columnName.substring(0,1).toUpperCase() + columnName.substring(1);
                htmlRows.append("<th>").append(columnName).append("</th>");
            }
            htmlRows.append("</tr>");

            while (resultSet.next())
            {
                htmlRows.append("<tr align=\"left\">");
                for (int i = 2; i <= columnCount ; i++)
                {
                    htmlRows.append("<td>").append(resultSet.getString(i)).append("</td>");
                }
                htmlRows.append("</tr>");
            }

            htmlRows.append("</table>");

            return htmlRows.toString();
        }
        catch (Exception ex)
        {
            Logger.getLogger(HtmlTable.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }
}
